package com.example.casspringbootdemo.demos.conf;

import net.unicon.cas.client.configuration.CasClientConfigurerAdapter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Map;

@Configuration
public class CasAuthConfig extends CasClientConfigurerAdapter {

    /**
     * 自定义认证跳转策略
     * @param authenticationFilter
     */
    @Override
    public void configureAuthenticationFilter(FilterRegistrationBean authenticationFilter) {
        Map<String, String> initParameters = authenticationFilter.getInitParameters();
        //这里CustomAuthRedirectStrategy的类路径根据自身项目进行调整
        initParameters.put("authenticationRedirectStrategyClass", "com.example.casdemo.demos.conf.CustomAuthRedirectStrategy");
    }

    /**
     * 配置CAS的验证过滤器

     * */
    @Override
    public void configureValidationFilter(FilterRegistrationBean validationFilter) {
        Map<String, String> initParameters = validationFilter.getInitParameters();
        initParameters.put("encodeServiceUrl", "false");
    }

    /**
     * 跨域过滤器
     *解决跨域问题
     * @return
     */
    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean<CorsFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new CorsFilter(source));
        registrationBean.setOrder(-2147483648);
        return registrationBean;
    }
}
